#include "Init.h"
#include "Engine.h"
#include "DBCHandler.h"
#include "ScreenHandler.h"
#include "SocketCommunicator.h"
#include "ClientHandler.h"
#include "ServerHandler.h"
#include "WorldHandler.h"
#include "Logging.h"
#include "Config.h"
#include "time.h"

void init()
{
	srand(time(NULL));
	logMessage("Akuma II Started.");

	globalConfig.loadConfig();
	
	std::string serverIP = globalConfig.getServerIP();

	globalDBCHandler.loadAllDBCs();
	globalScreenHandler.setup();
	globalWorldHandler.setupTown();

	if(globalConfig.getIsServer() == true)
	{
		ServerHandler* serverHandler = new ServerHandler();
		globalCSHandler = serverHandler;
		globalWorldHandler.setupNewPlayer(globalConfig.getLocalPlayerName(), core::vector3df(0,0,0)); 
	}
	else
	{
		ClientHandler* clientHandler = new ClientHandler();
		globalCSHandler = clientHandler;
		//globalCSHandler->setDelay(1);
	}

	globalCSHandler->start();

	if(globalConfig.getIsServer() == true)
	{
		logMessage("Akuma II server started.");
		globalScreenHandler.appendToChatLog("[SERVER]: Akuma II server started.\n");
		engine();
	}
	else
	{
		logMessage("Joining Akuma II server at IP " + serverIP + ".");
		USLEEP(500);
		engine();
#if 0
		unsigned int timeout = 500;
		unsigned int i = 0;
		while(timeout > i++)
		{
			if(globalCSHandler->getHasConnection() == true)
			{
				break;
			}

			USLEEP(1);
		}
		
		if(i < timeout)
		{
			engine();
		}
		else
		{
			logMessage("Could not connect to server at ip:\n" + serverIP);
		}
		#endif
	}

	//gaem stop at this point
	std::string playerName = globalConfig.getLocalPlayerName();
	if(globalConfig.getIsServer() == true)
	{
		globalCSHandler->addToSendQueue(reinterpret_cast<uintptr_t>(&playerName), SHUTDOWN);
	}
	else
	{
		globalCSHandler->addToSendQueue(reinterpret_cast<uintptr_t>(&playerName), DISC);
	}
	USLEEP(50);
	
	globalCSHandler->stop();

	logMessage("Akuma II exiting.");
}
